<%@ page language="java" contentType="text/html; charset=utf-8" %>
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page"/>
<jsp:useBean id="bb" class="weaver.general.BaseBean"/>
<%@ page import="biweekly.util.org.apache.commons.codec.binary.Base64" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="okhttp3.*" %>
<%
    JSONObject jsonData = new JSONObject();
    try {
        String token = getAccessToken();
        jsonData.put( "result", token);
    }catch (Exception e){
        e.printStackTrace();
        out.print("同步代码运行异常");
    }

    out.print( jsonData.toJSONString() );
%>
<%!
    /**
     * 获取token
     *
     * @return
     */
    private static String getAccessToken() {
        final String URL = "http://10.10.11.114";
        // private static final String CLIENT_ID = "f339304e-3fe4-4f4d-8745-39d8b76db35c";测试
        final String CLIENT_ID = "b61c89e1-5a72-40e0-b9ad-d873e8a3da67";
        // private static final String SECURET = "ZjE0NzMzMWUtZjVhOS00ZjVkLWE3NjAtNWNmMWVlZGY0NGQ0";测试
        final String SECURET = "NTBjZjI1NjUtYmNiMy00ZDdiLTkxN2QtYjM1MmMyMTI0Yjkz";

        String tokenUrl = URL + "/oauth/token";
        String authStr = CLIENT_ID.concat(":").concat(SECURET);
        String authStrEnc = new String(Base64.encodeBase64(authStr.getBytes()));
        String accessToken = "";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("grant_type", "client_credentials")
                    .addFormDataPart("scope", "write")
                    .build();
            Request request = new Request.Builder()
                    .url(tokenUrl)
                    .method("POST", body)
                    .addHeader("Authorization", "Basic ".concat(authStrEnc))
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            if (!"".equals(result)) {
                JSONObject resultJson = JSONObject.parseObject(result);
                accessToken = resultJson.getString("access_token");
            }
            System.out.println("response=" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }

%>